package com.lzq.springboot_lzq.controller;

import com.lzq.springboot_lzq.pojo.Dept;
import com.lzq.springboot_lzq.pojo.ResponseMessage;
import com.lzq.springboot_lzq.pojo.dto.DeptDto;
import com.lzq.springboot_lzq.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@RestController // 接口方法返回对象,转换成json文本
@RequestMapping("/dept") // localhost:3939/user/**
public class DeptController {

    @Autowired
    IDeptService deptService;

    //restful风格
    //增加
    @PostMapping ("/add")  // localhost:3939/user method=post
    public ResponseMessage<Dept> add(@Validated @RequestBody DeptDto dept){
        Dept deptNew = deptService.add(dept);
        return ResponseMessage.success(deptNew);
    }

    //删除
    @DeleteMapping ("/delete/{id}")
    public ResponseMessage<Dept> delete(@PathVariable int id) {
        Dept dept = deptService.findById(id);
        if (dept != null) {
            deptService.delete(id);
            return ResponseMessage.success(dept);
        } else {
            return ResponseMessage.error(null);
        }
    }

    //修改
    @PutMapping("/edit")
    public ResponseMessage<Dept> edit(@Validated @RequestBody DeptDto deptNew) {
        Dept dept = deptService.findById(deptNew.getId());
        if (dept != null) {
            dept = deptService.edit(deptNew);
            return ResponseMessage.success(dept);
        } else {
            return ResponseMessage.error(null);
        }
    }

    //查询
    @GetMapping("/getById/{id}")
    public ResponseMessage<Dept> get(@PathVariable int id) {
        Dept dept = deptService.findById(id);
        if (dept != null) {
            return ResponseMessage.success(dept);
        } else {
            return ResponseMessage.error(null);
        }
    }
    // 查询所有用户并按ID从大到小排序
    @GetMapping("/getAll")
    public ResponseMessage<Iterable<Dept>> findAll() {
        Iterable<Dept> depts = deptService.findAll();
        return ResponseMessage.success(depts);
    }
}
